﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;

namespace DeleteitemsConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string url;
            string listname;
            int itemstotdelete;
            string removetilldate;
            if (args.Length <= 2)
            {
                ShowHelp();
            }
            else
            {
                GetParameters(args, out url, out listname, out itemstotdelete, out removetilldate);

                if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(listname) && itemstotdelete!=0)
                {
                    

                    DateTime starttime = DateTime.Now;
                    DateTime endtime;
                    try
                    {
                        SPSecurity.RunWithElevatedPrivileges(
                        delegate()
                        {
                            Console.WriteLine("past runelevated");


                            using (SPSite site = new SPSite(url))
                            {
                                Console.WriteLine("past site open");
                                using (SPWeb web = site.OpenWeb())
                                {
                                    Console.WriteLine("past web open");
                                    web.AllowUnsafeUpdates = true;
                                    SPList List = web.Lists[listname];
                                    Console.WriteLine("past assign of list");

                                    SPQuery query = new SPQuery();
                                    if (!string.IsNullOrEmpty(removetilldate))
                                    {
                                        query.Query = string.Format("<Where><Lt><FieldRef Name='Modified' /><Value IncludeTimeValue='TRUE' Type='DateTime'>{0}T00:00:23Z</Value></Lt></Where>", removetilldate);
                                    }
                                    query.ViewFields = "<FieldRef Name='ID'/>";
                                    query.IncludePermissions = false;
                                    int rowlimit = 2000;
                                    if (itemstotdelete < 2000)
                                    {
                                        rowlimit = itemstotdelete;

                                    }
                                    query.RowLimit = Convert.ToUInt32(rowlimit);


                                    // first get all the id's to be deleted 

                                    int m = 0;
                                    while (m < itemstotdelete)
                                    {
                                        int l = 0;
                                        ArrayList al = new ArrayList();

                                        SPListItemCollection myItems = List.GetItems(query);
                                        Console.WriteLine("query loaded 2000 items");
                                        foreach (SPListItem item in myItems) // note use enumeration 
                                        {

                                            al.Add(item.ID.ToString());
                                            Console.WriteLine(string.Format("item added {0}", l));
                                            l++;
                                        }
                                        Console.WriteLine("array loaded");

                                        query.ListItemCollectionPosition = myItems.ListItemCollectionPosition;
                                        Console.WriteLine("query loaded in collection");

                                        //while (query.ListItemCollectionPosition != null) ;
                                        //Console.WriteLine("item collection is not null");

                                        if (query.ListItemCollectionPosition != null)
                                        {
                                            Console.WriteLine("item collection is not null");
                                        }
                                        StringBuilder sbDelete = new StringBuilder();
                                        sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                                        string listguid = List.ID.ToString();
                                        int bcount = 0;
                                        Console.WriteLine("before xmlbatch is generated");
                                        for (int i = 0; i < al.Count; i++)
                                        {
                                            // Console.WriteLine(string.Format("xml aangemaakt voor {0}"), bcount);
                                            if (bcount > 1000)
                                            {
                                                sbDelete.Append("</Batch>");
                                                web.ProcessBatchData(sbDelete.ToString());
                                                Console.WriteLine("first 1000 deleted");
                                                sbDelete = new StringBuilder();
                                                sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                                                bcount = 0;

                                            }
                                            bcount++;
                                            sbDelete.Append("<Method>");
                                            sbDelete.Append("<SetList Scope=\"Request\">" + listguid + "</SetList>");
                                            sbDelete.Append("<SetVar Name=\"ID\">" + al[i].ToString() + "</SetVar>");
                                            sbDelete.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                                            sbDelete.Append("</Method>");
                                            Console.WriteLine(string.Format("added to batch {0}", i));
                                            m++;
                                        }
                                        Console.WriteLine("end of creating xmlbatch loop ");
                                        sbDelete.Append("</Batch>");
                                        if (sbDelete.ToString() != "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch></Batch>")
                                        {
                                            web.ProcessBatchData(sbDelete.ToString());
                                            Console.WriteLine(string.Format("ready with delete of {0} items", m));


                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    web.AllowUnsafeUpdates = false;
                                    // When your are finished re-enable it
                                }

                            }


                        });
                        endtime = DateTime.Now;
                        Console.WriteLine(string.Format("READY with delete of 50000 items start at {0} and end time {1} ", starttime, endtime));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
                else
                {
                    ShowHelp();
                }

            }
        }
        static void ShowHelp()
        {
            Console.WriteLine("\n\n\nDelete Lists tool By http://KbWorks.nl \n\n");
            Console.WriteLine("ex.\nDeleteitemsConsole siturl=urlofsite listname=nameoflist itemstodelete=2000 removetilldate=2010-08-01 ");
            Console.WriteLine("Note: Arguments may be in any order. date format ='yyyy-mm-day' and it is smaller then that date");
            Console.WriteLine("the date is optional and will be queried on the modified date");
        }
        static void GetParameters(string[] args, out string url, out string listname, out int itemstotdelete, out string removetilldate)
        {
            url = string.Empty;
            listname = string.Empty;
            itemstotdelete = 0;
            removetilldate = string.Empty;
            //override defaults with command line arguments
            foreach (string arg in args)
            {
                string[] pair = arg.Split('=');
                switch (pair[0].ToLower())
                {
                    case "siturl":
                        url = pair[1];
                        break;

                    case "listname":
                        listname = pair[1];
                        break;

                    case "itemstodelete":
                        itemstotdelete = Convert.ToInt32(pair[1]);
                        break;
                    case "removetilldate":
                        removetilldate = pair[1];
                        break;


                }
            }
        }

    }
}
